package com.dflc.controller.SystemController;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dflc.common.CommonConstant;
import com.dflc.entity.po.SysMenu;
import com.dflc.entity.po.SysRoleMenu;
import com.dflc.entity.po.TBackLoginUser;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.req.MenuReq;
import com.dflc.mapper.SysMenuMapper;
import com.dflc.mapper.SysRoleMenuMapper;
import com.dflc.service.SysMenuService;
import com.dflc.service.TBackLoginUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统菜单Controller控制器
 *
 * @author tqx
 * @site tqx
 * @company 数字涪陵
 */
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Resource
    private SysMenuService sysMenuService;
    @Resource
    private SysMenuMapper sysMenuMapper;
    @Resource
    private TBackLoginUserService tBackLoginUserService;
    @Resource
    private SysRoleMenuMapper sysRoleMenuMapper;

    /**
     * 查询所有菜单信息
     *
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 查询所有菜单信息
     */
    @PostMapping("/list")
    public HttpResponseEntity list(@RequestBody MenuReq req) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            List<SysMenu> menuList = new ArrayList<>();
            TBackLoginUser tBackLoginUser = (TBackLoginUser) entity.getData();
            if (!ObjectUtils.isEmpty(tBackLoginUser) && tBackLoginUser.getIsAdmin().intValue() == CommonConstant.BackIsAdmin.Yes) {
                // 是超级管理员
                menuList = sysMenuService.list(new QueryWrapper<SysMenu>().orderByAsc("order_num")
                        .eq("state", CommonConstant.StateActive.Active)
                        .and(wrapper -> wrapper.eq("type", req.getType()))
                );
                return HttpResponseEntity.success(sysMenuService.buildTreeMenu(menuList));
            } else {
                //不是超级管理员则不能查询
                return HttpResponseEntity.error(500, "您没有权限查询菜单信息");
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }


    /**
     * 根据id查询
     *
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 根据id查询
     */
    @GetMapping("/{id}")
    public HttpResponseEntity findById(@PathVariable(value = "id") Long id) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            SysMenu sysMenu = sysMenuService.getById(id);
            return HttpResponseEntity.success(sysMenu);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }


    /**
     * 添加或者修改
     *
     * @param sysMenu Description: 添加或者修改
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     */
    @PostMapping("/save")
    public HttpResponseEntity save(@RequestBody @Valid SysMenu sysMenu) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            if (StringUtils.isEmpty(sysMenu.getType())){
                sysMenu.setType(CommonConstant.MenuPermsType.PC);//默认新增管理端菜单
            }
            if (!sysMenu.getMenuType().equals(CommonConstant.MenuType.M)) {
                //不是目录则校验菜单和功能的权限标识符
                Map<String, Object> params3 = new HashMap<>();
                params3.put("perms", sysMenu.getPerms());
                List<SysMenu> list = sysMenuMapper.findAllByMap(params3);
                if (ObjectUtils.isEmpty(sysMenu.getId())) {
                    //新增时候要判断该权限的标识符是否已经存在
                    if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                        return HttpResponseEntity.error(500, "该权限标识符已存在！");
                    }
                    sysMenuService.save(sysMenu);
                } else {
                    //修改时候要判断该权限的标识符是否已经存在
                    if (!ObjectUtils.isEmpty(list) && list.size() > 0 && list.get(0).getId().intValue() != sysMenu.getId().intValue()) {
                        return HttpResponseEntity.error(500, "该权限标识符已存在！");
                    }
                    sysMenuService.updateById(sysMenu);
                }
            }else {
                //目录则要校验路径是否重复
                if (ObjectUtils.isEmpty(sysMenu.getPath())){
                    return HttpResponseEntity.error(500, "目录路径不能为空！");
                }
                Map<String, Object> params3 = new HashMap<>();
                params3.put("path", sysMenu.getPath());
                List<SysMenu> list = sysMenuMapper.findAllByMap(params3);
                if (ObjectUtils.isEmpty(sysMenu.getId())) {
                    //新增时候要判断该目录的路径是否已经存在
                    if (!ObjectUtils.isEmpty(list) && list.size() > 0) {
                        return HttpResponseEntity.error(500, "该目录路径已存在！");
                    }
                    sysMenuService.save(sysMenu);
                } else {
                    //修改时候要判断该目录的路径是否已经存在
                    int b = sysMenu.getId().intValue();
                    if (ObjectUtils.isEmpty(list)){
                        sysMenuService.updateById(sysMenu);
                    }else if (!ObjectUtils.isEmpty(list) && list.size() > 0 ) {
                        int a = list.get(0).getId().intValue();
                        if ( a != b) {
                            return HttpResponseEntity.error(500, "该目录路径已存在！");
                        }else {
                            sysMenuService.updateById(sysMenu);
                        }
                    }
                }
            }
            return HttpResponseEntity.success("操作成功！");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }

    /**
     * 删除
     *
     * @param id Description: 删除
     * @return HttpResponseEntity
     * @author tqx
     * @date 2023/6/6 11:30
     */
    @GetMapping("/delete/{id}")
    public HttpResponseEntity delete(@PathVariable(value = "id") Long id) {
        try {
            Integer userId = StpUtil.getLoginIdAsInt();
            HttpResponseEntity entity = tBackLoginUserService.findUserIsAdminByUserId(userId);
            if (entity.getStatus() != 200) {
                return entity;
            }
            int count = Math.toIntExact(sysMenuService.count(new QueryWrapper<SysMenu>().eq("parent_id", id)
                    .eq("state", CommonConstant.StateActive.Active)));
            if (count > 0) {
                return HttpResponseEntity.error(500, "请先删除子菜单！");
            }
            SysMenu sysMenu = sysMenuService.getById(id);
            if (ObjectUtils.isEmpty(sysMenu)) {
                return HttpResponseEntity.error(500, "菜单不存在！");
            }
            //查询该菜单与角色的关系是否有存在的绑定
            Map<String, Object> params2 = new HashMap<>();
            params2.put("menuId", id);
            List<SysRoleMenu> list2 = sysRoleMenuMapper.findAllByMap(params2);
            if (!ObjectUtils.isEmpty(list2) || list2.size() > 0) {
                return HttpResponseEntity.error(500, "该菜单已绑定角色，请先解除绑定！");
            }
            sysMenu.setState(CommonConstant.StateActive.Deleted);
            sysMenuService.saveOrUpdate(sysMenu);
            return HttpResponseEntity.success("删除成功！");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.getMessage());
        }
    }


}
